package com.founder.helloworldapp;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class TrackLineOverlay extends Overlay {
	
	private List<Location> locations;
	
	private List<Point> drawPoints;
	
	private double minLength = 5;
	
	public TrackLineOverlay(List<Location> locations) {
		this.locations = locations;
		drawPoints = new ArrayList<Point>();
	}
	
	public double computerLength(Point startPoint, Point stopPoint) {
		double x = stopPoint.x - startPoint.x;
		double y = stopPoint.y - startPoint.y;
		return Math.sqrt(x*x + y*y);
	}
	
	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {
		// 创建和设置你的绘图刷
		Paint paint = new Paint();
		paint.setColor(Color.GREEN);
		paint.setAntiAlias(true);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeWidth(3);
		Projection projection = mapView.getProjection();
		if (shadow) {
			//Draw annotations on the shadow layer
		} else {
			//Draw annotations on main map layer
			Point startPoint = new Point();
			Point stopPoint = new Point();
			drawPoints.clear();
			for (int i = 0; i < locations.size(); i++) {
				Location l = locations.get(i);
				GeoPoint geoPoint = new GeoPoint((int)l.getLatitude(), (int)l.getLongitude());
				
				if (i == 0) {
					projection.toPixels(geoPoint, startPoint);
					projection.toPixels(geoPoint, stopPoint);
					drawPoints.add(new Point(startPoint.x, startPoint.y));
				}
				
				projection.toPixels(geoPoint, stopPoint);
				double length = computerLength(startPoint, stopPoint);
				if ((length < minLength) && (i < locations.size() - 1)) {
					continue;
				}
				drawPoints.add(new Point(stopPoint.x, stopPoint.y));
				
				projection.toPixels(geoPoint, startPoint);
			}
			Log.d("hello", "allCount=" + locations.size() + ",drawCount=" + drawPoints.size() + ",level=" + mapView.getZoomLevel());

			for (int i = 0; i < drawPoints.size() - 1; i++) {
				startPoint = drawPoints.get(i);
				stopPoint = drawPoints.get(i + 1);
				canvas.drawLine(startPoint.x, startPoint.y, stopPoint.x, stopPoint.y, paint);
			}
		}
	}

	@Override
	public boolean onTap(GeoPoint point, MapView mapView) {
		// 如果这个覆盖处理了屏幕接触，就返回true  
		return false;
	}
}
